﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ODP.Helper;
using System.Net.Json;
using ODP.Model;

namespace ODP.QQCrawler
{
    public partial class MainForm : Form
    {
        #region 属性
        bool m_isLogin = false;

        public bool IsLogin
        {
            get { return m_isLogin; }
            set { m_isLogin = value; }
        }

        private int m_appKeyIndex = 1;

        public int AppKeyIndex
        {
            get { return m_appKeyIndex; }
            set { m_appKeyIndex = value; }
        }

        private string m_AppKey;

        public string AppKey
        {
            get { return Helper.GetAppKey(m_appKeyIndex); }
            set { m_AppKey = value; }
        }
        private string m_AppSecret;

        public string AppSecret
        {
            get { return Helper.GetAppSecret(m_appKeyIndex); }
            set { m_AppSecret = value; }
        }

        private IDictionary<string, bool> m_Users = new Dictionary<string, bool>();

        public IDictionary<string, bool> Users
        {
            get { return m_Users; }
            set { m_Users = value; }
        }

        private IList<CheckBoxListItem> cbliList = new List<CheckBoxListItem>();

        private DateTime m_beginDateTime;

        private DateTime m_currentUserBeginDateTime;

        private bool m_pause = false;

        public bool Pause
        {
            get { return m_pause; }
            set { m_pause = value; }
        }
        #endregion


        public MainForm()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
            backgroundWorker1.WorkerReportsProgress = true;
            new InitHelper().InitCheckBoxListItem(ref cbliList);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            string a = this.AppKey;

            if (!IsLogin)
            {
                //
                Login l = new Login();

                if (l.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
                {
                    QQAPI.QQAPI qqAPI = new QQAPI.QQAPI();

                    string result = qqAPI.GetCurrentUserInfo(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType);

                    SetCurrentUserInfoToControl(result);

                    //请求自己的首页,开发寻找用户信息
                    GetMayKownPerson();

                    BindCatalog();
                }
                else
                {
                    this.Close();
                    Application.Exit();
                }
            }
        }

        private void GetMayKownPerson()
        {
            QQAPI.QQAPI qqAPI = new QQAPI.QQAPI();
            string result = qqAPI.GetMayKownPerson(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType);

            JsonTextParser jtp = new JsonTextParser();

            string users = JsonHelper.GetValueByName(result, "data");

            if (!string.IsNullOrEmpty(users))
            {
                JsonObjectCollection jac = jtp.Parse("{" + users + "}") as JsonObjectCollection;
                if (jac != null && jac.Count >0)
                {
                    foreach (var item in jac["data"] as JsonArrayCollection)
                    {
                        var name = JsonHelper.GetValueByName(item.ToString(), "name");

                        if (!string.IsNullOrEmpty(name) && !Users.ContainsKey(name))
                        {
                            Users.Add(name, false);
                        }
                    }
                }
            }

            if (Users.Count == 0)
            {
                Pause = true;
            }

            lbwaitSearch.Text = "待搜索用户数:" + Users.Count.ToString();
        }

        private void SetCurrentUserInfoToControl(string result)
        {
            this.lbfansnum.Text += JsonHelper.GetValueByName(result, "fansnum");
            this.lbidolnum.Text += JsonHelper.GetValueByName(result, "idolnum");
            this.lbisvip.Text += JsonHelper.GetValueByName(result, "isvip");
            this.lblocation.Text += JsonHelper.GetValueByName(result, "location");

            this.lbnick.Text += JsonHelper.GetValueByName(result, "nick");
            this.lbsex.Text += JsonHelper.GetValueByName(result, "sex") == "0"?"女":"男";
            this.lbtweetnum.Text += JsonHelper.GetValueByName(result, "tweetnum");
            this.lbuserid.Text += JsonHelper.GetValueByName(result, "name");
            this.lbsismyidol.Text += JsonHelper.GetValueByName(result, "verifyinfo");
        }

        private void cbAutoStop_CheckedChanged(object sender, EventArgs e)
        {

        }

        #region 多线处理用户信息
        /// <summary>
        /// 多线处理用户信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (!Pause)
            {
                string result = "";
                QQAPI.QQAPI qqAPI = new QQAPI.QQAPI();
                var items = Users.Where(p => !p.Value).ToDictionary(p => p.Key, p => p.Value);

                int i = 0;

                QueryStringParameter qspnames = new QueryStringParameter("name", "");

                if (items.Count > 0)
                {
                    #region 对用户进行一些相关操作
                    foreach (var item in items)
                    {

                        QueryStringParameter qsp = new QueryStringParameter("name", item.Key);

                        qspnames.Value += item.Key + ",";

                        //获取到用户信息
                        result = qqAPI.GetOtherUserInfo(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType, qsp);

                        //显示当前用户信息
                        SetSearchUserInfoToControl(result);

                        //动作
                        #region 进行各项互动动作

                        //添加特殊收听
                        if (cbaddspecial.Checked)
                        {
                            result = qqAPI.AddSpecialFriends(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType, qsp);
                        }
                        //获取微博消息

                        //获取评论信息

                        //获取转播信息

                        #endregion

                        //获取当前搜索用户的听友,并添加到待搜索用户列表中

                        //标记为已爬虫
                        Users[item.Key] = true;

                        i++;
                        backgroundWorker1.ReportProgress(i);

                        System.Threading.Thread.Sleep(1000 * 10);
                    }

                    if (qspnames.Value.EndsWith(","))
                    {
                        qspnames.Value = qspnames.Value.Remove(qspnames.Value.Length - 1, 1);
                    }

                    //添加朋友
                    if (cbevent_invite.Checked)
                    {
                        //qqAPI.InviteFriends(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType, qspnames);
                    }

                    //添加收听
                    if (cbaddfans.Checked)
                    {
                        result = qqAPI.AddFriends(ODP.Com.Current.OAuth, ODP.Com.Current.OAuth.twitterType, qspnames);
                    }
                    #endregion
                }
                else
                {
                    GetMayKownPerson();
                }
            }
        }

        private void SetSearchUserInfoToControl(string result)
        {
            this.lbsfansnum.Text = "粉丝数：" + JsonHelper.GetValueByName(result, "fansnum");
            this.lbsidolnum.Text = "关注人数：" + JsonHelper.GetValueByName(result, "idolnum");
            this.lbsisvip.Text = "是否认证用户：" + JsonHelper.GetValueByName(result, "isvip");
            this.lbslocation.Text = "所在地：" + JsonHelper.GetValueByName(result, "location");

            this.lbsnick.Text = "昵称：" + JsonHelper.GetValueByName(result, "nick");
            this.lbssex.Text = "性别：" + JsonHelper.GetValueByName(result, "sex") == "0" ? "女" : "男";
            this.lbstweetnum.Text = "已发微博数：" + JsonHelper.GetValueByName(result, "tweetnum");
            this.lbsuserid.Text = "用户ID：" + JsonHelper.GetValueByName(result, "name");
            this.lbsismyidol.Text = "是否为当前登陆用户粉丝：" + JsonHelper.GetValueByName(result, "ismyidol");
        }

        private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int hasSearchcount = Users.Where(p=>p.Value).Count();
            lbhasSearch.Text = "已搜索用户数：" + hasSearchcount.ToString();
            lbwaitSearch.Text = "待搜索用户数：" + (Users.Count - hasSearchcount).ToString();
            allusedTime.Text = "所有用户已耗时：" + DateTime.Now.Subtract(m_beginDateTime).TotalSeconds;
            currentUsedTime.Text = "当前用户已耗时：" + DateTime.Now.Subtract(m_currentUserBeginDateTime).TotalSeconds;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            while (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();

                if (Pause)
                {
                    break;
                }
            }
        }
        #endregion

        private void button1_Click(object sender, EventArgs e)
        {
            if (m_beginDateTime != null)
            {
                m_beginDateTime = DateTime.Now;
            }
            if (m_currentUserBeginDateTime != null)
            {
                m_currentUserBeginDateTime = DateTime.Now;
            }
            Pause = false;

            while (!backgroundWorker1.IsBusy)
            {
                backgroundWorker1.RunWorkerAsync();

                if (Pause)
                {
                    break;
                }
            }
        }

        private void BindCatalog()
        {
            foreach(CheckBoxListItem cbli in cbliList)
            {
                clbCatalog.Items.Add(cbli.Text);
            }
        }
    }
}
